package com.baidu.bos.web.action.base;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.bos.utils.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	protected T model;
	protected PageBean pageBean = new PageBean();
	protected DetachedCriteria detachedCriteria;

	public BaseAction() {
		// 获得父类类型
		ParameterizedType genericSuperclass = null;
		Type type = this.getClass().getGenericSuperclass();
		if (type instanceof ParameterizedType) {
			genericSuperclass = (ParameterizedType) type;
		}else {
			genericSuperclass = (ParameterizedType) this.getClass().getSuperclass().getGenericSuperclass();
		}
		// 获得父类泛型的数组
		Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
		Class<T> domainClass = (Class<T>) actualTypeArguments[0];
		detachedCriteria = DetachedCriteria.forClass(domainClass);
		pageBean.setDetachedCriteria(detachedCriteria);
		try {
			model = domainClass.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 用fastjson将Object序列化为json对象响应到浏览器
	public void writeObject2Json(Object obj) {
		// 将json数据响应给客户端
		ServletActionContext.getResponse().setContentType(
				"text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().print(JSON.toJSONString(obj,SerializerFeature.DisableCircularReferenceDetect));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public T getModel() {
		return model;
	}

	public void setPage(int page) {
		pageBean.setCurrentPage(page);
	}

	public void setRows(int rows) {
		pageBean.setPageSize(rows);
	}
}
